package com.mdd.front.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.goods.OrderGoods;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.service.AnnualService;
import com.mdd.common.entity.goods.GoodsSpecification;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.goods.OrderGoodsMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.mapper.service.AnnualServiceMapper;
import com.mdd.common.mapper.specification.GoodsSpecificationMapper;
import com.mdd.common.utils.TimeUtil;
import com.mdd.front.service.service.IAnnualServiceService;
import com.mdd.front.validate.PageParam;
import com.mdd.front.validate.service.AnnualServiceParam;
import com.mdd.front.vo.service.AnnualServiceDetailVo;
import com.mdd.front.vo.service.AnnualServiceListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 包年服务使用记录实现类
 */
@Service
public class AnnualServiceServiceImpl extends ServiceImpl<AnnualServiceMapper, AnnualService> implements IAnnualServiceService {


    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private GoodsSpecificationMapper goodsSpecificationMapper;
    @Resource
    private OrderMapper orderMapper;


    /**
     * 包年服务使用记录列表
     *
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<AnnualServiceListVo>
     */
    @Override
    public PageResult<AnnualServiceListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        String startDate = params.get("startDate");
        String endDate = params.get("endDate");
        String orderId = params.get("orderId");

        // 获取秒
        Integer start = Math.toIntExact(TimeUtil.dateToTimestamp(startDate));
        Integer end = Math.toIntExact(TimeUtil.dateToTimestamp(endDate));

        LambdaQueryWrapper<AnnualService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AnnualService::getOrderId, orderId);
        lambdaQueryWrapper.between(AnnualService::getDate, start, end);
        lambdaQueryWrapper.eq(AnnualService::getIsDelete, GlobalConstant.NOT_DELETE);
        Page<AnnualService> annualServicePage = this.baseMapper.selectPage(new Page<>(page, limit), lambdaQueryWrapper);

        List<AnnualServiceListVo> list = new LinkedList<>();
        annualServicePage.getRecords().forEach(annualService -> {
            AnnualServiceListVo vo = new AnnualServiceListVo();
            BeanUtils.copyProperties(annualService, vo);
            vo.setDate(TimeUtil.timestampToDate(Long.valueOf(annualService.getDate()), "yyyy-MM-dd"));
            vo.setCreateTime(TimeUtil.timestampToDate(annualService.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(annualService.getUpdateTime()));
            list.add(vo);
        });

        return PageResult.iPageHandle(annualServicePage.getTotal(), annualServicePage.getCurrent(), annualServicePage.getSize(), list);
    }

    /**
     * 包年服务使用记录详情
     *
     * @param id 主键参数
     * @return AnnualService
     */
    @Override
    public AnnualServiceDetailVo detail(Integer id) {
        AnnualService model = this.baseMapper.selectOne(
                new QueryWrapper<AnnualService>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        AnnualServiceDetailVo vo = new AnnualServiceDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 包年服务使用记录新增
     *
     * @param annualServiceParam 参数
     */
    @Override
    public void add(AnnualServiceParam annualServiceParam) {
        LambdaQueryWrapper<AnnualService> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AnnualService::getIsDelete, GlobalConstant.NOT_DELETE);
        queryWrapper.eq(AnnualService::getDate, TimeUtil.dateToTimestamp(annualServiceParam.getDate()));
        queryWrapper.eq(AnnualService::getOrderId, annualServiceParam.getOrderId());
        AnnualService annualService = this.baseMapper.selectOne(queryWrapper);
        Assert.isNull(annualService, "该天已经预约");

        OrderGoods orderGoods = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoods>()
                .eq(OrderGoods::getOrderId, annualServiceParam.getOrderId()));
        GoodsSpecification goodsSpecification = goodsSpecificationMapper.selectOne(new LambdaQueryWrapper<GoodsSpecification>()
                .eq(GoodsSpecification::getGoodsSpecificationId, orderGoods.getGoodsId())
                .eq(GoodsSpecification::getIsDelete, GlobalConstant.NOT_DELETE));
        Integer i = this.baseMapper.selectCount(new LambdaQueryWrapper<AnnualService>()
                .eq(AnnualService::getIsDelete, GlobalConstant.NOT_DELETE)
                .eq(AnnualService::getOrderId, annualServiceParam.getOrderId()));
        if(Objects.nonNull(goodsSpecification.getPreferentialQuantity()) &&
                Integer.parseInt(goodsSpecification.getPreferentialQuantity()) <= i){
            throw new OperateException("已经预约满了，不能继续预约了");
        }

        AnnualService model = new AnnualService();
        model.setOrderId(annualServiceParam.getOrderId());
        model.setDate(Math.toIntExact(TimeUtil.dateToTimestamp(annualServiceParam.getDate())));
        // 新增是预约
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getId, annualServiceParam.getOrderId())
                .eq(Order::getIsDelete, GlobalConstant.NOT_DELETE));
        // 设置用户确定了保姆后直接将保姆分配给用户的地方
        if(StringUtils.hasText(order.getStaffIds())){
            model.setStaffId(Integer.valueOf(order.getStaffIds()));
        }
        model.setStatus(GlobalConstant.NOT_DELETE);
	    this.baseMapper.insert(model);
    }

    /**
     * 包年服务使用记录编辑
     *
     * @param annualServiceParam 参数
     */
    @Override
    public void edit(AnnualServiceParam annualServiceParam) {
        AnnualService model = this.baseMapper.selectOne(
                new QueryWrapper<AnnualService>()
                    .eq("id",  annualServiceParam.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(annualServiceParam.getId());
        model.setOrderId(annualServiceParam.getOrderId());
        model.setStaffId(annualServiceParam.getStaffId());
        model.setDate(Math.toIntExact(TimeUtil.dateToTimestamp(annualServiceParam.getDate())));
        model.setStatus(annualServiceParam.getStatus());
	    this.baseMapper.updateById(model);
    }

    /**
     * 包年服务使用记录删除
     *
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        AnnualService model = this.baseMapper.selectOne(
                new QueryWrapper<AnnualService>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
	    this.baseMapper.updateById(model);
    }

    @Override
    public AnnualServiceDetailVo getOrderNum(Integer orderId, Integer userId) {
        // 查询服务总次数
        LambdaQueryWrapper<OrderGoods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(OrderGoods::getOrderId, orderId);
        OrderGoods orderGoods = orderGoodsMapper.selectOne(goodsLambdaQueryWrapper);
        LambdaQueryWrapper<GoodsSpecification> goodsSpecificationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsSpecificationLambdaQueryWrapper.eq(GoodsSpecification::getGoodsSpecificationId, orderGoods.getGoodsId());
        goodsSpecificationLambdaQueryWrapper.eq(GoodsSpecification::getIsDelete, GlobalConstant.NOT_DELETE);
        GoodsSpecification goodsSpecification = goodsSpecificationMapper.selectOne(goodsSpecificationLambdaQueryWrapper);
        Integer all = Integer.parseInt(goodsSpecification.getPreferentialQuantity());
        // 可以预约数量 商品总次数-订单数据的非删除总和
        LambdaQueryWrapper<AnnualService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AnnualService::getOrderId, orderId);
        lambdaQueryWrapper.eq(AnnualService::getIsDelete, GlobalConstant.NOT_DELETE);
        Integer xiadanshu = this.baseMapper.selectCount(lambdaQueryWrapper);
        // 已完成 查询状态为1的
        lambdaQueryWrapper.eq(AnnualService::getStatus, GlobalConstant.DELETE);
        Integer used = this.baseMapper.selectCount(lambdaQueryWrapper);
        // 待使用 商品总次数-已完成
        AnnualServiceDetailVo annualServiceDetailVo = new AnnualServiceDetailVo();
        annualServiceDetailVo.setOrderId(orderId);
        annualServiceDetailVo.setUsed(used);
        annualServiceDetailVo.setToBeUse(all - used);
        annualServiceDetailVo.setSum(all - xiadanshu);
        return annualServiceDetailVo;
    }

}
